#pragma once
#include <unordered_map>
#include <websocketpp/server.hpp>
#include <websocketpp/config/asio_no_tls.hpp>
#include <mutex>

typedef websocketpp::server<websocketpp::config::asio> websocket_server;

class online_manager
{
public:
    //进入游戏大厅,游戏大厅连接建立成功后立即调用
    void enter_game_hall(uint64_t uid,const websocket_server::connection_ptr &conn)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        _game_hall.insert(std::make_pair(uid, conn));
    }

    //退出游戏大厅,游戏大厅连接断开后立即调用
    void exit_game_hall(uint64_t uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        _game_hall.erase(uid);
    }

    //进入游戏房间,游戏房间建立成功后立即调用
    void enter_game_room(uint64_t uid,const websocket_server::connection_ptr &conn)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        _game_room.insert(std::make_pair(uid, conn));
    }

    void exit_game_room(uint64_t uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        _game_room.erase(uid);
    }

    //判断用户是否在游戏大厅
    bool is_game_hall(uint64_t uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        auto it = _game_hall.find(uid);
        if(it == _game_hall.end())
        {
            return false;
        }
        return true;
    }

    //判断用户是否在游戏房间
    bool in_game_room(uint64_t uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        auto it = _game_room.find(uid);
        if(it == _game_room.end())
        {
            return false;
        }
        return true;
    }

    //从游戏大厅中获取指定用户关联的socket连接
    bool get_conn_from_game_hall(uint64_t uid,websocket_server::connection_ptr &conn)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        auto it = _game_hall.find(uid);
        if(it == _game_hall.end())
        {
            return false;
        }
        conn = it->second;
        return true;
    }

    //从游戏房间获取指定用户关联的socket连接
    bool get_conn_from_game_room(uint64_t uid,websocket_server::connection_ptr &conn)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        auto it = _game_room.find(uid);
        if(it == _game_room.end())
        {
            return false;
        }
        conn = it->second;
        return true;
    }
private:
    //游戏大厅的客户端连接 管理
    std::unordered_map<uint64_t, websocket_server::connection_ptr> _game_hall;
    //游戏房间的客户端连接管理
    std::unordered_map<uint64_t, websocket_server::connection_ptr> _game_room;
    std::mutex _mutex;
};